package com.pengheng.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.pengheng.props.ClickHouseProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.pengheng.mapper.clickhouse", sqlSessionTemplateRef = "clickHouseSqlSessionTemplate")
public class ClickHouseDataSourceConfig {

    @Resource
    private ClickHouseProperties clickHouseProperties;

    @Bean(name = "clickHouseDataSource")
    public DataSource clickHouseDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(clickHouseProperties.getUrl());
        dataSource.setUsername(clickHouseProperties.getUsername());
        dataSource.setPassword(clickHouseProperties.getPassword());
        dataSource.setDriverClassName(clickHouseProperties.getDriverClassName());
        return dataSource;
    }

    @Bean(name = "clickHouseSqlSessionFactory")
    public SqlSessionFactory clickHouseSqlSessionFactory(@Qualifier("clickHouseDataSource") DataSource clickHouseDataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(clickHouseDataSource);
        return bean.getObject();
    }

    @Bean(name = "clickHouseTransactionManager")
    public PlatformTransactionManager clickHouseTransactionManager(@Qualifier("clickHouseDataSource") DataSource clickHouseDataSource) {
        return new DataSourceTransactionManager(clickHouseDataSource);
    }

    @Bean(name = "clickHouseSqlSessionTemplate")
    public SqlSessionTemplate clickHouseSqlSessionTemplate(@Qualifier("clickHouseSqlSessionFactory") SqlSessionFactory clickHouseSqlSessionFactory) {
        return new SqlSessionTemplate(clickHouseSqlSessionFactory);
    }
}